#!/usr/bin/env python

import time
import sys
import socket
import webbrowser
import argparse

from db_sqlite import *
from data_getjson import *
from file_output import *

def showWelcome():
    print '''\n    CScanner v1.0 - Scanning The C Segment\n    http://sjf.la\n\n[!] legal disclaimer: usage of cscanner for scanning'''

def showUsage():
	print '\nUsage: python ./cscanner.py [options]\n'
	print 'Options:'
	print '  -h, --help\t\tShow help message and exit'
	print '  -u URL\t\tTarget url'
	print '  -d DEPTH\t\tScanning depth'

def getNowTime():
	nowTime = time.localtime(time.time())
	return time.strftime("%H:%M:%S", nowTime)

def showStart():
	print '\n[*] startting at ', getNowTime(), ''

def showEnd():
	print '\n[*] shutting down at ', getNowTime(), '\n'
	exit()

def getConfigLDict(argvs):
	"""
	get the dict from sys.argv
	"""
	tred_dict = {}
	i = 1
	while (i<=(len(argvs)-1)) :
		tred_dict[argvs[i]] = argvs[i+1] 
		i += 2
	return tred_dict	

def soc_getIP(targetURL):
	"""
	translate the url to ip
	"""
	try:
		dst_addr = socket.getaddrinfo(targetURL, 'http')[0][4][0]
	except socket.gaierror, e:
		print "\nCan not get messages of this domain ."
		showEnd()
	return dst_addr
def getAddrPref(targetArgs):
	"""
	get the addr prefix *.*.*
	"""
	addr_dict = targetArgs.i.split('.')
	addrPref = addr_dict[0]+'.'+addr_dict[1]+'.'+addr_dict[2]
	return addrPref

def getTargetArgs():
	"""
	get the command line args
	"""
	parser = argparse.ArgumentParser(prog="python ./cscanner.py", description="The C segment scanner.")
	parser.add_argument('-u', metavar='URL', required=True, help='the target url')
	parser.add_argument('-d', metavar='DEPTH', type=int, help='the depth will be scanning')
	parser.add_argument('-o', metavar='OUTPUT', help='output the result data')
	args = parser.parse_args()
	return args

def main():
	"""
	CScanner main
	"""
	targetArgs = getTargetArgs()
	targetArgs.i = soc_getIP(targetArgs.u)
	print "\nStart Scanning "+targetArgs.u+"["+targetArgs.i+"] ...\n"
	conn = sql_getConn()
	cur = sql_getCur(conn)
	isExisted = sql_isURLExist(cur, targetArgs)
	if (isExisted ==-1):
		#exit
		showEnd()
	elif (isExisted==1):
		#return None and then Insert new data
		sql_insertURL(conn, cur, targetArgs)
	else :
		#Update old data
		sql_updateURL(conn, cur, targetArgs)

	#create CS result table
	isCreated = sql_createCSTable(conn, cur, targetArgs)
	if (isCreated ==-1):
		#user exit
		showEnd()
	elif (isCreated ==0):
		#table has existed
		print "Table had existed, please delete it first!"
		showEnd()
	else :
		#table created
		print 'The CS result table ['+isCreated+'] created successfully!\n'
		
	#get the api key
	dst_addr_pref = getAddrPref(targetArgs)
	dst_addr_suf = 1
	while (dst_addr_suf!=255):
		temp_ip = dst_addr_pref+".%i" % dst_addr_suf
		print temp_ip
		xml_data = data_bingSearch(temp_ip)
		if (xml_data ==-1):
			#this ip do not have data
			dst_addr_suf += 1
			continue
		#precess the xml data
		dst_addr_suf += 1
		resultList = trXmlToList(xml_data)
		if (resultList!=-1):
			sql_insertCSResult(conn, cur, targetArgs, resultList, temp_ip)
		else:
			continue
	output(conn, cur, targetArgs)
	
	showEnd()

def output(conn, cur, targetArgs):
	dst_addr = sql_getIpbyURL(conn, cur, targetArgs)
	if (dst_addr==-1):
		print "\nThe URL had not checked yet."
		showEnd()
	isExist = sql_isRSTableExist(conn, cur, targetArgs)
	if (isExist==-1):
		print "\nThe target "+targetArgs.u+" does not exist."
		showEnd()
	resultList = sql_getRSList(conn, cur, isExist)
	fileURL = file_outputHtml(resultList, isExist)
	print "\nThe data outputes to file '"+fileURL+"'"
	webbrowser.open(fileURL)
